package com.niit.ai.dl.dltrain.service;

import com.niit.ai.dl.dltrain.web.model.FileUploadRsp;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class FileService implements InitializingBean {
    private static final Logger LOG = LoggerFactory.getLogger(FileService.class);

    @Value("${niit.ai.upload.dir}")
    private String rootDir;

    public FileUploadRsp uploadModel(MultipartFile file, HttpServletRequest request) throws IOException {
        String subDir = "model";
        String savedFilePath = this.upload(file, subDir, request);

        FileUploadRsp rsp = new FileUploadRsp();
        rsp.setFilePath(savedFilePath);
        return rsp;
    }

    public FileUploadRsp uploadSample(MultipartFile file, HttpServletRequest request) throws IOException {
        String subDir = "sample";
        String savedFilePath = this.upload(file, subDir, request);

        FileUploadRsp rsp = new FileUploadRsp();
        rsp.setFilePath(savedFilePath);
        return rsp;
    }

    public String upload(MultipartFile file, String subDir, HttpServletRequest request) throws IOException {
        // 上传文件到指定目录
        String newFileName = generateNewFileName(file.getOriginalFilename());
        String newFilePath = FilenameUtils.concat(subDir, newFileName);
        String fullFilePath = FilenameUtils.concat(rootDir, newFilePath);

        File dest = new File(fullFilePath);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }

        file.transferTo(dest);
        LOG.info("upload success, file = {}", fullFilePath);

        return newFilePath;
    }

    public String downLoad(String filePath, HttpServletResponse response) throws Exception {
        String fullFilePath = FilenameUtils.concat(rootDir, filePath);
        File file = new File(fullFilePath);

        if (!file.exists()) {
            return "文件不存在:" + filePath;
        }
        response.setContentType("application/force-download");
        response.addHeader("Content-Disposition", "attachment;fileName=" + FilenameUtils.getName(filePath));
        OutputStream os = response.getOutputStream();

        FileUtils.copyFile(file, os);
        return "success";
    }

    private String generateNewFileName(String fileName) {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateString = df.format(new Date());

        String newfileName = "Upload" + "-" + dateString + "-" + fileName;
        return newfileName;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        new File(rootDir).mkdirs();
    }

}
